//
//  ClassesViewController.m
//  FlyGift
//
//  Created by lanou3g on 15/7/12.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "ClassesViewController.h"
#import "DetailStrategyViewController.h"

@interface ClassesViewController ()<UITableViewDataSource,UITableViewDelegate>

@property(nonatomic,assign)int offset;

@property(nonatomic,strong)UITableView *searchRecord;

@end

@implementation ClassesViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.offset = 0;
}

#pragma mark --- 视图初始化解析
-(void)classTableViewRequestWithUrl:(NSString *)url
{
    NSString * string = [NSString stringWithFormat:url,self.offset];
    [LORequestManger GET:string success:^(id response) {
        NSDictionary * dictionary = (NSDictionary *)response;
        NSDictionary * dic = [dictionary objectForKey:@"data"];
        self.defaultModelArray = [NSMutableArray array];
        for (NSDictionary * dic1 in [dic objectForKey:@"items"]) {
            DefaultTableModel * model = [DefaultTableModel setValueWithDictionary:dic1];
            [self.defaultModelArray addObject:model];
        }
        [self loadTableView];
        [self.tableView reloadData];
        [self pullDownRefresh:string];
        [self pullUpLoadMoreWith:string];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark --- 轮播图跳转解析
-(void)classScrollViewRequestWithUrl:(NSString *)url
{
    [LORequestManger GET:url success:^(id response) {
        NSDictionary * dictionary = (NSDictionary *)response;
        NSDictionary * dic = [dictionary objectForKey:@"data"];
        self.defaultModelArray = [NSMutableArray array];
        for (NSDictionary * dic1 in [dic objectForKey:@"posts"]) {
            DefaultTableModel * model = [DefaultTableModel setValueWithDictionary:dic1];
            [self.defaultModelArray addObject:model];
        }

        self.navigationItem.title = [dic objectForKey:@"title"];
        [self loadTableView];
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}


#pragma mark --- 下拉刷新
-(void)pullDownRefresh:(NSString *)url
{
    __block typeof(self) blockSelf = self;
    [self.tableView addGifHeaderWithRefreshingBlock:^{
        [blockSelf tableViewPullDownRequest:url];
    }];
    
    self.tableView.header.updatedTimeHidden = YES;
    NSMutableArray * idleImages = [NSMutableArray array];
    for (int i = 0; i < 2; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_loading_action%d@2x",i+1]];
        [idleImages addObject:image];
    }
    [self.tableView.gifHeader setImages:idleImages forState:MJRefreshHeaderStateIdle];
    NSMutableArray * refreshingImages = [NSMutableArray array];
    for (int i = 0; i < 2; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_loading_action%d@2x",i+1]];
        [refreshingImages addObject:image];
    }
    [self.tableView.gifHeader setImages:refreshingImages forState:MJRefreshHeaderStateRefreshing];
    [self.tableView.header beginRefreshing];
}
-(void)tableViewPullDownRequest:(NSString *)string
{
    self.offset = 0;
    self.defaultModelArray = [NSMutableArray array];
    NSString * str = [NSString stringWithFormat:string,self.offset];
    [LORequestManger GET:str success:^(id response) {
        NSDictionary * dictionary = (NSDictionary *)response;
        NSDictionary * dic = [dictionary objectForKey:@"data"];
        for (NSDictionary * dic1 in [dic objectForKey:@"items"]) {
            DefaultTableModel * model = [DefaultTableModel setValueWithDictionary:dic1];
            [self.defaultModelArray addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];

}

#pragma mark --- 上拉加载
-(void)pullUpLoadMoreWith:(NSString *)string
{
    __block typeof(self) BLOCKSELF = self;
    [self.tableView addGifFooterWithRefreshingBlock:^{
        [BLOCKSELF tableViewPullUpRequest:string];
    }];
    NSMutableArray * refreshingImages = [NSMutableArray array];
    for (int i = 0; i < 2; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"icon_loading_action%d@2x",i+1]];
        [refreshingImages addObject:image];
    }
    self.tableView.gifFooter.refreshingImages = refreshingImages;
}
-(void)tableViewPullUpRequest:(NSString *)string
{
    self.offset += 20;
    NSString * str = [NSString stringWithFormat:string,self.offset];
    NSLog(@"%d",self.offset);
    [LORequestManger GET:str success:^(id response) {
        NSDictionary * dictionary = (NSDictionary *)response;
        NSDictionary * dic = [dictionary objectForKey:@"data"];
        for (NSDictionary * dic1 in [dic objectForKey:@"items"]) {
            DefaultTableModel * model = [DefaultTableModel setValueWithDictionary:dic1];
            [self.defaultModelArray addObject:model];
        }
        [self.tableView reloadData];
        [self.tableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

#pragma mark --- 表视图
-(void)loadTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kP6Height(104)) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self .tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [self addToTopButton];
    [self addSearchRecordTableView];
    [self addSearchRecordButton];
}

#pragma mark --- tableView 代理方法
//分区数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
//每分区行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.defaultModelArray.count;
}
//自定义cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIndentifier = @"defaultCell";
    [tableView registerClass:[DefaultViewTableViewCell class] forCellReuseIdentifier:cellIndentifier];
    DefaultViewTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    DefaultTableModel * model = self.defaultModelArray[indexPath.row];
    if (model.isClick)
    {
        [cell.likeButton setImage:[UIImage imageNamed:@"like_normal@2x"] forState:UIControlStateNormal];
    }
    else
    {
        [cell.likeButton setImage:[UIImage imageNamed:@"like_press@2x"] forState:UIControlStateNormal];
    }
    [cell.likeButton addTarget:self action:@selector(likeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    cell.titleLabel.text = model.title;
    cell.likeLabel.text = model.likes_count.stringValue;
    cell.likeButton.tag = indexPath.row + 100;
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:model.cover_image_url] placeholderImage:[UIImage imageNamed:@"placeHolder@2x.jpg"]];
    return cell;
}
//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (kScreenWidth - kP6width(10)) / 2.18 + kP6Height(8);
}

#pragma mark --- 点击cell触发
//跳转攻略详情
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailStrategyViewController * detailSVC = [[DetailStrategyViewController alloc]init];
    DefaultTableModel * model = self.defaultModelArray[indexPath.row];
    detailSVC.content_url = model.content_url;
    [self.navigationController pushViewController:detailSVC animated:YES];
}

#pragma mark --- 点击喜欢按钮
-(void)likeButtonAction:(UIButton *)button
{
    DefaultTableModel * model = self.defaultModelArray[button.tag - 100];
    DefaultViewTableViewCell * cell = (DefaultViewTableViewCell *)button.superview.superview.superview;
    if (model.isClick) {
        [cell.likeButton setImage:[UIImage imageNamed:@"like_press@2x"] forState:UIControlStateNormal];
        cell.likeLabel.text =  [NSString stringWithFormat:@"%d",model.likes_count.intValue];
        [MBProgressHUD showSuccess:@"已取消收藏"];
    }
    else
    {
        [cell.likeButton setImage:[UIImage imageNamed:@"like_normal@2x"] forState:UIControlStateNormal];
        cell.likeLabel.text =  [NSString stringWithFormat:@"%d",model.likes_count.intValue + 1];
        [MBProgressHUD showSuccess:@"收藏成功"];
    }
    model.isClick = !model.isClick;
}
#pragma mark --- 点击按钮回到顶部
-(void)addToTopButton
{
    UIButton * toTopButton = [UIButton buttonWithType:UIButtonTypeSystem];
    toTopButton.frame = CGRectMake(kScreenWidth - kP6width(60), kScreenHeight - kP6Height(220), kP6width(40), kP6width(40));
    [toTopButton setBackgroundImage:[UIImage imageNamed:@"home_back_top@3x"] forState:UIControlStateNormal];
    [toTopButton addTarget:self action:@selector(toTop) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:toTopButton];
}
-(void)toTop
{
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark --- 点击显示搜索记录
-(void)addSearchRecordButton
{
    UIButton * searchRecordButton = [UIButton buttonWithType:UIButtonTypeSystem];
    searchRecordButton.frame = CGRectMake(kScreenWidth - kP6width(60), kScreenHeight - kP6Height(270), kP6width(40), kP6width(40));
    [searchRecordButton setBackgroundImage:[UIImage imageNamed:@"icon_float_category_search@3x"] forState:UIControlStateNormal];
    [searchRecordButton addTarget:self action:@selector(searchRecordAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchRecordButton];
}
-(void)searchRecordAction
{
    self.searchRecord.hidden = !self.searchRecord.hidden;
}
-(void)addSearchRecordTableView
{
    self.searchRecord = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - kP6width(100), kScreenHeight) style:UITableViewStylePlain];
    self.searchRecord.backgroundColor = [UIColor lightGrayColor];
    [self.view addSubview:_searchRecord];
    self.searchRecord.hidden = YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
